//
// Created by zhengbo on 23-4-18.
//

#include <GL/gl.h>
#include "CameraImage.h"

CameraImage::CameraImage(cv::Mat image) {
    this->mImage = image;
    InitBuffer();
}

CameraImage::~CameraImage() {
    ReleaseBuffer();
}

void CameraImage::Update() {
    glBindTexture(GL_TEXTURE_2D, mTextureId);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, mImage.cols, mImage.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, mImage.data);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glBindTexture(GL_TEXTURE_2D, 0);
}

void CameraImage::Render() {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, mTextureId);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 1);
    glVertex3f(-1, -1, 0);
    glTexCoord2f(1, 1);
    glVertex3f(1, -1, 0);
    glTexCoord2f(1, 0);
    glVertex3f(1, 1, 0);
    glTexCoord2f(0, 0);
    glVertex3f(-1, 1, 0);
    glEnd();
    glBindTexture(GL_TEXTURE_2D, 0);
    glDisable(GL_TEXTURE_2D);
}

void CameraImage::ReleaseBuffer() {
    if (mTextureId != 0) {
        glDeleteTextures(1, &mTextureId);
        mTextureId = 0;
    }
}

void CameraImage::InitBuffer() {
    if (mTextureId == 0) {
        glGenTextures(1, &mTextureId);
    }
}